﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ufida.u9.ait.openapi.utils;
using UFIDA.U9.Base;
using UFIDA.U9.CBO.Pub.Controller;
using UFIDA.U9.CBO.SCM.Bin;
using UFIDA.U9.CBO.SCM.Warehouse;
using UFIDA.U9.InvDoc.TransferIn;
using UFIDA.U9.ISV.TransferInISV;
using UFIDA.U9.ISV.TransferInISV.Proxy;
using UFIDA.U9.SM.DealerSO;
using UFSoft.UBF.Business;

namespace ufida.u9.ait.openapi
{
    internal class TransferInBase
    {
        public static TransferIn ApproveDocEx(DocDTOData dto, TransferIn doc)
        {
            if (!String.IsNullOrEmpty(dto.DocDate))
            {
                //修改日期
                using (ISession session = Session.Open())
                {
                    doc.BusinessDate = DateTime.Parse(dto.DocDate);//单据日期
                    doc.SOBAccountPeriod = EntityUtils.getPostPeriod(doc.BusinessDate);//记账期间
                    if (doc.TransInAccountPeriods != null && doc.TransInAccountPeriods.Count > 0)
                    {
                        //记账期间
                        doc.TransInAccountPeriods[0].SOBAccountPeriod = doc.SOBAccountPeriod;
                    }

                    session.Commit();
                }
            }
            return ApproveDoc(doc);
        }

        public static TransferIn ApproveDoc(TransferIn doc)
        {
            doc = doc.Key.GetEntity();
            if (doc.Status == TransInStatus.Approved
                || doc.Status == TransInStatus.BizClose
                || doc.Status == TransInStatus.FIClose)
            {
                throw new Exception($"单号[{doc.DocNo}]状态为已审或关闭,不能审核");
            }

            TransferInBatchApproveSRV sv = new TransferInBatchApproveSRV();
            sv.DocList = new List<CommonArchiveDataDTO> {
                new CommonArchiveDataDTO() {
                    ID=doc.ID,
                    Code=doc.DocNo,
                }
            };
            sv.Do();

            return doc;
        }

        public static TransferIn CreateDoc(CopyOfIC_TransferInDTOData dto)
        {
            //预处理
            preSave(dto);
            IC_TransferInDTOData dto1 = new IC_TransferInDTOData();
            DTOUtils.DTOPropCopy(dto, dto1);
            dto1.DocNo = "";//清空单号,自动生成单号
            //生单,调用产业链服务
            CommonCreateTransferInSVProxy proxy = new CommonCreateTransferInSVProxy();
            proxy.TransferInDTOList = new List<IC_TransferInDTOData> { dto1 };
            List<CommonArchiveDataDTOData> ret = proxy.Do();
            //处理返回
            TransferIn doc = TransferIn.Finder.FindByID(ret[0].ID);
            return doc;
        }

        private static void preSave(CopyOfIC_TransferInDTOData dto)
        {
            //日期处理
            if (!String.IsNullOrEmpty(dto.BusinessDate1))
            {
                dto.BusinessDate=DateTime.Parse(dto.BusinessDate1);
            }
            //行处理
            foreach (var linedto in dto.TransInLines)
            {
                if (linedto.ItemInfo == null||string.IsNullOrEmpty(linedto.ItemInfo.ItemCode))
                    throw new Exception("必须传入料品[ItemInfo.ItemCode]");
                if (linedto.TransInWh == null||string.IsNullOrEmpty(linedto.TransInWh.Code))
                    throw new Exception("必须传入仓库[TransInWh.Code]");
                //校验仓库编码
                Warehouse wh1=EntityUtils.GetEntityByCode<Warehouse>(linedto.TransInWh.Code);
                if (linedto.TransInSubLines == null|| linedto.TransInSubLines.Count==0)
                    throw new Exception("必须传入调入单子行[TransInSubLines]");

                //单货位转换为多货位处理
                if (linedto.BinInfo != null && !string.IsNullOrEmpty(linedto.BinInfo.Code))
                {
                    linedto.TransInBins = new List<CopyOfIC_TransInBinDTOData>()
                        {
                            new CopyOfIC_TransInBinDTOData()
                            {
                                BinInfo=new CopyOfBinInfoData()
                                {
                                    Code=linedto.BinInfo.Code,
                                    Name=linedto.BinInfo.Name,
                                }
                            }
                        };
                }
                
                //调入货位处理
                if (linedto.TransInBins != null)
                {
                    foreach (var bindto in linedto.TransInBins)
                    {
                        if (bindto.BinInfo == null || string.IsNullOrEmpty(bindto.BinInfo.Code))
                            continue;

                        string path = $"Code='{bindto.BinInfo.Code}' and Warehouse.Code='{linedto.TransInWh.Code}'";
                        Bin bin = Bin.Finder.Find(path);
                        if (bin == null)
                        {
                            //调入库位不存在,直接创建
                            bin = CreateBin(linedto.TransInWh.Code, bindto.BinInfo);
                        }
                        bindto.BinInfo.Bin = bin.ID;
                    }
                }

                //调出行
                foreach (var sublinedto in linedto.TransInSubLines)
                {
                    if (sublinedto.TransOutWh == null||string.IsNullOrEmpty(sublinedto.TransOutWh.Code))
                        throw new Exception("必须传入调出仓库[TransOutWh.Code]");
                    //校验仓库编码
                    Warehouse wh2 = EntityUtils.GetEntityByCode<Warehouse>(sublinedto.TransOutWh.Code);

                    //单货位转多货位处理
                    if (sublinedto.BinInfo != null && !string.IsNullOrEmpty(sublinedto.BinInfo.Code))
                    {
                        sublinedto.TransInBins = new List<CopyOfIC_TransInBinDTOData>()
                            {
                                new CopyOfIC_TransInBinDTOData()
                                {
                                    BinInfo=new CopyOfBinInfoData()
                                    {
                                        Code = sublinedto.BinInfo.Code,
                                        Name = sublinedto.BinInfo.Name,
                                    }
                                }
                            };
                    }

                    //调出货位处理
                    if (sublinedto.TransInBins != null)
                    {
                        foreach (var bindto in sublinedto.TransInBins)
                        {
                            if (bindto.BinInfo == null || string.IsNullOrEmpty(bindto.BinInfo.Code))
                                continue;

                            string path = $"Code='{bindto.BinInfo.Code}' and Warehouse.Code='{sublinedto.TransOutWh.Code}'";
                            Bin bin = EntityUtils.GetEntityByPath<Bin>(path);
                            bindto.BinInfo.Bin = bin.ID;
                        }
                    }
                }
            }
        }

        private static Bin CreateBin(string whCode, CopyOfBinInfoData bindto)
        {
            Bin bin = null;
            string path = $"Org={Context.LoginOrg.ID} and Code='{whCode}'";
            Warehouse wh = Warehouse.Finder.Find(path);
            if (wh == null) throw new Exception($"查找存储地点失败,path:{path}");

            using (ISession session = Session.Open())
            {
                bin = Bin.Create();
                bin.Warehouse = wh;
                bin.Code = bindto.Code;
                if (string.IsNullOrEmpty(bindto.Name))
                    bin.Name = bindto.Code;
                else
                    bin.Name = bindto.Name;

                session.Commit();
            }

            return bin;
        }
    }
}
